// pages/learn/learn.js

Page({
  data: {
    currentWord: null,
    currentIndex: 0,
    words: [],
    wordBook: null
  },

  // 不认识这个单词
  notKnow() {
    this.recordResult(false)
    this.nextWord()
  },

  // 认识这个单词
  know() {
    this.recordResult(true)
    this.nextWord()
  },

  // 记录学习结果
  recordResult(isKnown) {
    const { currentWord, currentIndex, words } = this.data
    const app = getApp()

    // 更新用户进度
    if (!app.globalData.userProgress) {
      app.globalData.userProgress = {}
    }

    if (!app.globalData.userProgress[currentWord.id]) {
      app.globalData.userProgress[currentWord.id] = {
        correctCount: 0,
        wrongCount: 0
      }
    }

    if (isKnown) {
      app.globalData.userProgress[currentWord.id].correctCount++
    } else {
      app.globalData.userProgress[currentWord.id].wrongCount++
    }

    // 简单的复习算法 - 如果连续正确3次，则认为掌握
    if (app.globalData.userProgress[currentWord.id].correctCount >= 3) {
      words[currentIndex].mastered = true
      this.setData({
        words
      })
    }
  },

  // 下一个单词
  nextWord() {
    let { currentIndex, words } = this.data
    currentIndex++

    if (currentIndex >= words.length) {
      // 所有单词学习完毕
      wx.showModal({
        title: '学习完成',
        content: '恭喜您完成了当前单词本的学习！',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.setData({
      currentIndex,
      currentWord: words[currentIndex]
    })
  },

  onLoad: function(options) {
    // 获取当前选中的单词本
    const app = getApp()
    let wordBook = app.globalData.currentWordBook

    // 如果options中有wordBookId参数，则使用该参数
    if (options && options.wordBookId) {
      // 从全局单词本列表中查找对应ID的单词本
      const wordBooks = app.globalData.wordbooks || []
      wordBook = wordBooks.find(book => book.id === parseInt(options.wordBookId)) || wordBook
    }

    if (!wordBook) {
      wx.showToast({
        title: '请先选择单词本',
        icon: 'none',
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    // 从全局数据中加载当前单词本的单词
    const wordList = app.globalData.words[wordBook.id] || [];

    if (wordList.length === 0) {
      wx.showToast({
        title: '该单词本暂无单词数据',
        icon: 'none',
        success: () => {
          wx.navigateBack();
        }
      })
      return;
    }

    // 检查是否有学习进度
    if (app.globalData.userProgress) {
      // 更新单词的掌握状态
      wordList.forEach(word => {
        if (app.globalData.userProgress[word.id] && app.globalData.userProgress[word.id].correctCount >= 3) {
          word.mastered = true;
        }
      });
    }

    this.setData({
      wordBook,
      words: wordList,
      currentIndex: 0,
      currentWord: wordList[0]
    })
  }
})